package com.fattyCorps.common.packet.hero.component;

import lombok.Getter;

import java.util.*;

public class Component {
    public interface ITrunk {
        <T extends IComponent> T addComponent(Class<T> cls);
        <T extends IComponent> T getComponent(Class<T> cls);
    }

    public interface IComponent {
        void onCreate(Object owner);
        void onInit();
        void onUpdate();
        void onEvent(int e, Object[] objs);
    }

    public static class Trunk implements ITrunk, Cloneable {
        @Getter
        private Map<Class, IComponent> components = new HashMap<>();
        private Object owner;

        public Trunk(Object owner) {
            this.owner = owner;
        }

        @Override
        public <T extends IComponent> T addComponent(Class<T> cls) {
            T t = null;
            try {
                t = cls.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            t.onCreate(owner);
            t.onInit();

            components.put(cls, t);
            return t;
        }

        @Override
        public <T extends IComponent> T getComponent(Class<T> cls) {
            return (T) components.get(cls);
        }

        public void onUpdate() {
            Iterator<Map.Entry<Class, IComponent>> iterator = components.entrySet().iterator();
            while (iterator.hasNext()) {
                iterator.next().getValue().onUpdate();
            }
        }

        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
}
